package com.base.cn.platform.os.service.user.exprule;

import com.base.cn.platform.os.common.mybatis.BaseBiz;
import com.base.cn.platform.os.common.mybatis.Pagination;
import com.base.cn.platform.os.common.utils.DataUtil;
import com.base.cn.platform.os.common.utils.DateUtils;
import com.base.cn.platform.os.common.utils.ObjectUtils;
import com.base.cn.platform.os.common.utils.StringUtils;
import com.base.cn.platform.os.dao.user.exprule.CusUserExpRecordDao;
import com.base.cn.platform.os.entity.user.exprule.CusUserExpAccount;
import com.base.cn.platform.os.entity.user.exprule.CusUserExpRecord;
import com.base.cn.platform.os.entity.user.exprule.CusUserExpRule;
import com.base.cn.platform.os.entity.user.exprule.CusUserExpRuleColumns;
import com.base.cn.platform.os.service.user.gradeconfig.CusUserGradeConfigBiz;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 经验记录Biz
 * Created by ll on 2018/4/20
 */
@Service
public class CusUserExpRecordBiz extends BaseBiz<CusUserExpRecord,CusUserExpRecordDao> {

    @Autowired
    private CusUserExpRuleBiz cusUserExpruleBiz;
    @Autowired
    private CusUserExpAccountBiz cusUserExpruleAccountBiz;
    @Autowired
    private CusUserGradeConfigBiz cusUserGradeConfigBiz;
    /**
     * 搜索经验记录列表
     * @param page
     * @param cusUserExpruleRecord
     * @return
     */
    public PageInfo<CusUserExpRecord> queryCusUserExpruleRecordPage(Pagination page,
                                                                    CusUserExpRecord cusUserExpruleRecord,
                                                                    List<String> containColumns,boolean expRule){
        String whereSql = this.whereSql(cusUserExpruleRecord);
        PageInfo<CusUserExpRecord> recordPageInfo =this.findPage(whereSql,page,containColumns);
        if (expRule){
            recordPageInfo.setList(setUserExpruleByCusUserExpruleRecords(recordPageInfo.getList()));
        }
        return recordPageInfo;
    }

    /**
     * 搜索经验记录列表
     * @param count
     * @param cusUserExpruleRecord
     * @return
     */
    public List<CusUserExpRecord> queryCusUserExpruleRecordList(Integer count,
                                                                CusUserExpRecord cusUserExpruleRecord,
                                                                List<String> containColumns,boolean expRule){
        String whereSql = this.whereSql(cusUserExpruleRecord);
        List<CusUserExpRecord> cusUserExpRecords =this.find(whereSql,count,containColumns);
        if (expRule){
            return setUserExpruleByCusUserExpruleRecords(cusUserExpRecords);
        }
        return cusUserExpRecords;
    }



    /**
     * 添加积分记录
     * @param userExpruleRecord  用户Id
     */
    public CusUserExpRecord saveCusUserExpruleRecord(CusUserExpRecord userExpruleRecord){
       if(ObjectUtils.isNotEmpty(userExpruleRecord)){
           this.save(userExpruleRecord);
           return userExpruleRecord;
       }
        return null;
    }

    /**
     * 条件搜索语句
     * @param cusUserExpruleRecord
     * @return
     */
    public String  whereSql(CusUserExpRecord cusUserExpruleRecord){
        StringBuilder whereSql = new StringBuilder(" 1 = 1");
        if(ObjectUtils.isNotEmpty(cusUserExpruleRecord)){
            if(ObjectUtils.isNotEmpty(cusUserExpruleRecord.getUserId())){
                whereSql .append( " and userId =").append(cusUserExpruleRecord.getUserId());
            }
            if(ObjectUtils.isNotEmpty(cusUserExpruleRecord.getRuleId())){
                whereSql .append(" and ruleId =").append(cusUserExpruleRecord.getRuleId());
            }
            if(ObjectUtils.isNotEmpty(cusUserExpruleRecord.getOtherId())){
                whereSql .append( " and otherId=").append(cusUserExpruleRecord.getOtherId());
            }
            if(StringUtils.isNotEmpty(cusUserExpruleRecord.getDepict())){
                whereSql .append( " and depict like concat ('%','").append(cusUserExpruleRecord.getDepict()).append("','%')");
            }
            if (StringUtils.isNotEmpty(cusUserExpruleRecord.getCreateTime())){
                String nowTime = DateUtils.format(cusUserExpruleRecord.getCreateTime(), "yyyy-MM-dd");
                whereSql.append(" and DATE_FORMAT(createTime,'%Y-%m-%d')='").append(nowTime).append("'");
            }
        }
        whereSql .append(" order by id desc");
        return whereSql.toString();
    }


    /**
     * 添加经验行为数据
     * @param userGradeExpRecords
     */
    public List<CusUserExpRecord> setUserExpruleByCusUserExpruleRecords(List<CusUserExpRecord> userGradeExpRecords){
        if(ObjectUtils.isNotEmpty(userGradeExpRecords)){
            String ruleIds = userGradeExpRecords.stream().map(e->e.getRuleId().toString()).distinct().collect(Collectors.joining(","));
            if(StringUtils.isNotEmpty(ruleIds)){
                CusUserExpRuleColumns cusUserExprule = new CusUserExpRuleColumns();
                cusUserExprule.setIds(ruleIds);
                Map<BigDecimal,CusUserExpRule> userExpruleMap =cusUserExpruleBiz.queryCusUserExpRuleMap(cusUserExprule,null,new ArrayList<>());
                if(ObjectUtils.isNotEmpty(userExpruleMap)){
                    for(CusUserExpRecord userGradeExpRecord:userGradeExpRecords){
                        if(userExpruleMap.get(userGradeExpRecord.getRuleId())!=null){
                            userGradeExpRecord.setCusUserExprule(userExpruleMap.get(userGradeExpRecord.getRuleId()));
                        }
                    }
                }
            }
        }
        return userGradeExpRecords;
    }

    /**
     * 获取经验
     * @param type 1固定经验，2百分比
     * @param exp 规则中的经验,type==1固定，type==2时为获取otherScore的百分比
     * @param otherExp 外界传入的经验
     * @return 返回处理后的经验
     */
    private int getExp(int type,int exp,int otherExp){
        if(type==1){//1固定积分
            return  exp;
        }
        if(type==2){//2百分比
            double tga = 100D;
            double scale = Double.parseDouble(String.valueOf(exp)) / tga;
            double _otherExp = Double.parseDouble(String.valueOf(otherExp));
            double _exp = _otherExp * scale;
            return  new Double(_exp).intValue();
        }
        return 0;
    }



    /**
     * 批量添加经验记录
     * @param userId 用户ID
     * @param userExpruleList 积分规则列表
     * @param otherId 使用在特殊添加经验
     */
    public void saveBatchUserExpRecordList(BigDecimal userId, List<CusUserExpRule> userExpruleList, BigDecimal otherId){
        if(ObjectUtils.isNotEmpty(userExpruleList) && DataUtil.idIsNotNull(userId)){
            List<CusUserExpRecord> userGradeExpRecordList = new ArrayList<>();
            CusUserExpAccount userExpruleAccount = cusUserExpruleAccountBiz.queryUserGradeByUserId(userId);
            int _lv = cusUserGradeConfigBiz.queryUserLevel(userExpruleAccount.getExp());
            boolean times = false;
            if(_lv>=6){
                times = true;
            }
            long _exp = userExpruleAccount.getExp();
            for(CusUserExpRule userExprule : userExpruleList){
                int score = this.getExp(userExprule.getType(),userExprule.getScore().intValue(),0);
                if(times){
                    score = score * 2;
                }
                int exp = userExpruleAccount.getExp().intValue();
                userExpruleAccount.setExp(new Long(exp + score));

                CusUserExpRecord record = new CusUserExpRecord();
                record.setUserId(userId);
                record.setRuleId(userExprule.getId());
                record.setExp(userExprule.getScore().intValue());
                record.setOtherId(otherId);
                record.setDepict(userExprule.getTermDepict());
                userGradeExpRecordList.add(record);
            }
            if(_exp!=userExpruleAccount.getExp().longValue()){
                cusUserExpruleAccountBiz.updateById(userExpruleAccount,null);
                this.batchSave(userGradeExpRecordList);
            }
        }
    }

}
